import { createCommander } from '../plugins/command.plugin'
import { cloneDeep } from 'lodash'

let dragData = {
    before: [],
    after: [],
}
let isExeInit = false;

// 创建一个组件
export function createVisualCommand({
    focusData = { foucs: [], unFocus: [] },
    updateBlocks,
    dataModal,
    dragstart,
    dragend,
}) {
    const commander = createCommander(); // 注册命令数

    // 删除命令
    commander.registry({
        name: "delete",
        keyboard: [
            'backspace',
            'delete',
            'ctrl+d',
        ],
        execute: () => {
            // 命令被执行时要做的事情
            console.log('执行删除命令');
            let data = {
                before: dataModal.blocks || [],
                after: focusData.unFocus,
            }
            return {
                redo: () => {
                    // 重新做一遍，要做的事情
                    console.log('重做删除命令');
                    updateBlocks(data.after);
                },
                undo: () => {
                    // 将做的事情还原
                    console.log('撤回删除命令');
                    updateBlocks(data.before);
                },
            }
        }
    })

    // 拖拽命令，适用于三种情况
    // -从菜单拖拽组件到容器，
    // 在容器中拖拽组件调整位置，
    commander.registry({
        name: "drag",
        init: () => {
            const handler = {
                dragstart: () => {
                    // console.log('newBlock', dataModal.blocks);
                    // TODO dataModal.blocks 一直不更新？？？
                    dragData.before = cloneDeep(dataModal.blocks || [])
                },
                dragend: () => commander.state.commands.drag()
            }

            dragstart.on(handler.dragstart)
            dragend.on(handler.dragend)

            return () => { // 销毁
                dragstart.off(handler.dragstart)
                dragend.off(handler.dragend)
            }
        },
        execute: (blocks) => {
            // 命令被执行时要做的事情
            let before = cloneDeep(dragData.before)
            let after = cloneDeep(dataModal.blocks || [])
            console.log('执行移动命令', before, after);
            return {
                redo: () => {
                    // 重新做一遍，要做的事情
                    console.log('重做移动命令', cloneDeep(after));
                    updateBlocks(cloneDeep(after));
                },
                undo: () => {
                    // 将做的事情还原
                    console.log('撤回移动命令', cloneDeep(before));
                    updateBlocks(cloneDeep(before));
                },
            }
        }
    })

    if (!isExeInit) {
        isExeInit = true
        commander.init()
    }

    return {
        undo: () => commander.state.commands.undo(),
        redo: () => commander.state.commands.redo(),
        delete: () => commander.state.commands.delete(),
        drag: () => commander.state.commands.drag(),
    }
}